package com.nf.loginsystem.util;

import java.sql.*;

/**
 * @author 小志
 * @date 2024/11/5 - 16:22
 */
public class DBUtil {
    private static final String URL="jdbc:sqlserver://localhost:1433;DatabaseName=loginsystem;Encrypt=false";
    private static final String DRIVER="com.microsoft.sqlserver.jdbc.SQLServerDriver";
    private static final String USER="sa";
    private static final String PASSWORD="root";

    static {
        try {
            //自动加载驱动
            Class.forName(DRIVER);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取数据库连接
     * @return 返回连接对象
     */
    public static Connection getConnection(){
        try {
            return DriverManager.getConnection(URL,USER,PASSWORD);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 关闭释放资源
     * @param resultSet 结果集
     * @param statement 预处理对象
     * @param connection 数据库连接
     */
    public static void close(ResultSet resultSet, Statement statement, Connection connection){
        /*关闭结果集对象*/
        try {
            if(resultSet != null){
                resultSet.close();
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        /*关闭预处理对象*/
        try {
            if(statement != null){
                statement.close();
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        /*关闭数据库连接*/
        try {
            if(connection != null){
                connection.close();
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
